package com.fiap.seguranca.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.fiap.jpautil.JpaUtil;

public class GenericDao<T> {
	
	private final EntityManager em;
	private final Class<T> klass;	

	
	public GenericDao(EntityManager em, Class<T> klass) {
		this.em = em;
		this.klass = klass;
	}	
	
	public T salvar(T obj){
		
		this.em.getTransaction().begin();
		this.em.persist(obj);
		this.em.getTransaction().commit();
		
		return obj;
	}
	
	public T buscar(long id){
		return em.getReference(klass, id);
		
	}
	
	public List<T> lista(){
		return em.createQuery("select e from " + klass.getName() + " e").getResultList();
	}
	
	public void deletar(long id){		
		T obj =  this.buscar(id);
		em.remove(obj);

	}
	
	public T update(T obj) {

		em.getTransaction().begin();
		em.merge(obj);
		em.getTransaction().commit();
		
		return obj;
	}

}

